package com.example.demo1.controller;


import com.example.demo1.entity.User;
import com.example.demo1.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Controller
@RequestMapping("user")
public class LoginController {

    @Autowired
    private UserService userService;

    @RequestMapping("toLogin")
    public String show(){
        return "login";
    }


    @ResponseBody
    @RequestMapping("loginUser")
    public String login(User user, HttpServletRequest request){
        System.out.println(user);
        String userName = user.getUserName();
        String passWord = user.getPassWord();
        User user1 = userService.login(userName,passWord);
        if (user1 == null){
            return "用户名或密码错误";
        }else {
            request.getSession().setAttribute("user_session",user);
            return "登录成功";
        }

    }

    @RequestMapping("toRegister")
    public String toRegister(){
        return "register";
    }

    @RequestMapping("register")
    public String register(User user){
        int flag = userService.register(user);
        if (flag == 0){
            System.out.println("----------");
        }

        return "welcome";
    }


    @RequestMapping("welcome")
    public String welcome(){
        return "welcome";
    }

    @RequestMapping("outUser")
    public void outUser(HttpServletRequest request, HttpServletResponse response){
        request.getSession().removeAttribute("user_session");
        try {
            response.sendRedirect("/user/toLogin");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}
